<template>
  <div class="resume-chat">
    <!-- 侧边栏：历史会话 -->
    <aside class="sidebar">
      <el-button type="primary" plain @click="createNewChat">+ 新对话</el-button>
      <el-scrollbar>
        <div
          v-for="c in chatList"
          :key="c.id"
          :class="['chat-item', { active: c.id === currentChatId }]"
          @click="switchChat(c.id)"
        >
          {{ c.title }}
        </div>
      </el-scrollbar>
    </aside>

    <!-- 主区域 -->
    <main class="main-panel">
      <!-- 消息列表 -->
      <div ref="chatBox" class="chat-box">
        <div
          v-for="msg in messages"
          :key="msg.id"
          :class="['bubble', msg.role]"
        >
          <div v-if="msg.role === 'assistant'" class="avatar ai">AI</div>
          <div class="content">
            <MdPreview v-if="msg.role === 'assistant'" :text="msg.content" />
            <span v-else>{{ msg.content }}</span>
          </div>
          <div v-if="msg.role === 'user'" class="avatar user">U</div>
        </div>
      </div>

      <!-- 底部输入 -->
      <div class="input-area">
        <!-- 文件上传 -->
        <el-upload
          class="file-btn"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="selectFile"
        >
          <el-button circle><el-icon><Upload /></el-icon></el-button>
        </el-upload>

        <el-input
          v-model="inputText"
          type="textarea"
          :rows="1"
          placeholder="输入需求或上传简历后提问"
          @keydown.enter.prevent="sendMessage"
        />
        <el-button type="primary" :loading="sending" @click="sendMessage">
          发送
        </el-button>
      </div>
    </main>
  </div>
</template>
<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import axios from '@/utils/request'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
// import MdPreview from '@/components/MdPreview.vue'

/* ========== 类型定义 ========== */
interface Message {
  id: string
  role: 'user' | 'assistant'
  content: string
  file?: string
}

interface ChatSession {
  id: string
  title: string
}

/* ========== 响应式状态 ========== */
const chatList      = ref<ChatSession[]>([])
const messages      = ref<Message[]>([])
const currentChatId = ref<string>('')
const inputText     = ref<string>('')
const sending       = ref<boolean>(false)
const chatBox       = ref<HTMLElement>()     // 滚动容器
const currentFile   = ref<string>()          // 仅保存文件名

/* ========== 生命周期 ========== */
onMounted(async () => {
  const { data } = await axios.get<ChatSession[]>('/api/chat/')
  chatList.value = data
  if (data.length) await switchChat(data[0].id)
})

/* ========== 会话操作 ========== */
const createNewChat = async () => {
  const { data } = await axios.post<ChatSession>('/api/chat/')
  chatList.value.unshift(data)
  await switchChat(data.id)
}

const switchChat = async (id: string) => {
  currentChatId.value = id
  const { data } = await axios.get<Message[]>(`/api/chat/${id}/messages/`)
  messages.value = data
  scrollBottom()
}

/* ========== 消息发送 ========== */
const sendMessage = async () => {
  if (!inputText.value.trim()) return

  // 1. 本地立即渲染用户消息
  const userMsg: Message = {
    id: Date.now().toString(),
    role: 'user',
    content: inputText.value,
    file: currentFile.value
  }
  messages.value.push(userMsg)
  inputText.value = ''
  scrollBottom()

  // 2. 调后端
  sending.value = true
  try {
    const { data } = await axios.post<Message>(
      `/api/chat/${currentChatId.value}/messages/send/`,
      { content: userMsg.content, file: userMsg.file }
    )
    messages.value.push(data)          // 渲染 AI 回复
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || '发送失败')
  } finally {
    sending.value = false
    currentFile.value = undefined
    scrollBottom()
  }
}

/* ========== 文件选择 ========== */
const selectFile = (file: any) => {
  currentFile.value = file.name
  ElMessage.success(`已选择 ${file.name}`)
}

/* ========== 滚动到底 ========== */
const scrollBottom = () => nextTick(() => {
  chatBox.value?.scrollTo({ top: chatBox.value.scrollHeight, behavior: 'smooth' })
})
</script>

<style scoped lang="scss">
.resume-chat {
  display: flex;
  height: 100vh;
  background: #f5f7fa;
}
.sidebar {
  width: 240px;
  background: #fff;
  border-right: 1px solid #e6e8eb;
  padding: 12px;
  .chat-item {
    padding: 8px 12px;
    margin: 4px 0;
    border-radius: 4px;
    cursor: pointer;
    &.active {
      background: #ecf5ff;
      color: #409eff;
    }
  }
}
.main-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.chat-box {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}
.bubble {
  display: flex;
  margin-bottom: 12px;
  &.user {
    justify-content: flex-end;
    .avatar { order: 2; margin-left: 8px; }
  }
  &.assistant {
    justify-content: flex-start;
    .avatar { margin-right: 8px; }
  }
}
.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #fff;
  &.ai { background: #409eff; }
  &.user { background: #67c23a; }
}
.content {
  max-width: 70%;
  background: #fff;
  border-radius: 8px;
  padding: 8px 12px;
}
.input-area {
  display: flex;
  align-items: flex-end;
  padding: 12px;
  border-top: 1px solid #e6e8eb;
  background: #fff;
  gap: 8px;
  .file-btn {
    margin-right: 4px;
  }
}
</style>